# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _

from .draw_nuonuo import create_fapiao, read_fapiao, invalid_fapiao
from .draw_nuonuo import print_batch_fapiao, print_fapiao


import logging

_logger = logging.getLogger(__name__)


def nuonuo_request_method(fapiao):
    result = create_fapiao(fapiao)

    for rec in result:
        one = fapiao.browse(rec['id'])
        serial_num = rec['serial_num']

        one.write({
            'nuonuo_serial_num': serial_num,
            'nuonuo_api_status': 'doing',
            'nuonuo_api_status_msg': '开票中'})

    return result


def nuonuo_query_method(fapiao):
    records = read_fapiao(fapiao)

    for one in records:
        if one['api_status'] in ['done']:
            one['state'] = 'done'
        elif one['api_status'] in ['be_invalid']:
            # todo 暂时用不到. 什么叫做已经取消?
            one['state'] = 'be_invalid'
        elif one['api_status'] in ['doerror', 'signerror']:
            one['state'] = 'error'
        else:
            # doing, signing, being_invalid
            one['state'] = 'reread'

        for line in one['line_ids']:
            line['id'] = int(line['line_num'])

    for record in records:
        values_for_draw = {
            'nuonuo_api_status': record['api_status'],
            'nuonuo_api_status_msg': record['api_status_msg'],
            'nuonuo_api_fail_cause': record['api_fail_cause'],
        }

        one = fapiao.browse(record['id'])
        one.write(values_for_draw)

    return records


def nuonuo_invalid_method(fapiao):
    # print('nuonuo_invalid_method', fapiao)
    # _logger.info('nuonuo_invalid_method:%s,', fapiao)
    # time.sleep(3)
    records = invalid_fapiao(fapiao)

    # _logger.info('nuonuo_invalid_method ret:%s,', records)

    return records


def nuonuo_print_patch_method(fapiao):
    print('nuonuo_print_patch_method', fapiao)
    # time.sleep(3)
    res = print_batch_fapiao(fapiao)

    # string  return

    # {
    #     'ids': [],
    #     'result':  '',  batch id, a string for print encryptdata
    # }

    return [{'id': one.id} for one in fapiao]


def nuonuo_print_method(fapiao):
    print('nuonuo_print_method', fapiao)
    # time.sleep(3)
    records = print_fapiao(fapiao)

    print('nuonuo_print_method', records)

    return records

    # return [{'id': one.id} for one in fapiao]


class FapiaoDrawProvider(models.Model):
    _inherit = "fp.draw.provider"

    def _request_methods(self):
        result = super()._request_methods()
        result2 = result.copy()
        result2.update({'nuonuo': nuonuo_request_method})
        return result2

    def _query_methods(self):
        result = super()._query_methods()
        result2 = result.copy()
        result2.update({'nuonuo': nuonuo_query_method})
        return result2

    def _invalid_methods(self):
        result = super()._invalid_methods()
        result2 = result.copy()
        result2.update({'nuonuo': nuonuo_invalid_method})
        return result2

    def _print_methods(self):
        result = super()._print_methods()
        result2 = result.copy()
        result2.update({'nuonuo': nuonuo_print_method})
        return result2


class FapiaoDraw(models.Model):
    _inherit = "fp.fapiao.draw"

    # state = fields.Selection(
    #     selection_add=[
    #         ('being_invalid', 'being_invalid'),  # 作废中. 临时状态
    #         ('be_invalid', 'be_invalid'),  # 已作废. 末状态  稳定状态
    #     ])

    nuonuo_serial_num = fields.Char(readonly=True,  help="开票请求后, 返回的序列号")

    nuonuo_api_status = fields.Selection(selection=[
        ('done', 'done'),  # 开票成功
        ('doing', 'doing'),  # 开票中
        ('signing', 'signing'),  # 开票成功签章中
        ('doerror', 'doerror'),  # 开票失败
        ('signerror', 'signerror'),  # 开票成功签章失败
        ('be_invalid', 'be_invalid'),  # 已作废
        ('being_invalid', 'being_invalid'),  # 作废中
    ], string="开票api状态", readonly=True,
        help="开票查询, 返回的开票结果")

    nuonuo_api_status_msg = fields.Char('状态消息', readonly=True)
    nuonuo_api_fail_cause = fields.Char('失败原因', readonly=True)

    def unlink(self):
        self2 = self.filtered(lambda r: not r.nuonuo_serial_num)

        return super(FapiaoDraw, self2).unlink()

    def action_request(self):
        self2 = self
        if self[0].draw_provider_id.code == 'nuonuo':
            self2 = self.search([
                ('id', 'in', self.ids),
                ('state', '=', 'draft'),
                ('nuonuo_serial_num', '=', False)])
        super(FapiaoDraw, self2).action_request()

    def action_query(self):
        self2 = self
        if self[0].draw_provider_id.code == 'nuonuo':
            self2 = self.search(
                [('id', 'in', self.ids),
                 ('state', 'in', ['requested', 'reread']),
                 ('nuonuo_serial_num', '!=', False)])

        super(FapiaoDraw, self2).action_query()

    def action_invalid(self):
        # # 发票 作废
        self2 = self
        if self[0].draw_provider_id.code == 'nuonuo':
            self2 = self.search(
                [('id', 'in', self.ids),
                 ('state', 'in', ['done']),
                 ('nuonuo_serial_num', '!=', False)])

        super(FapiaoDraw, self2).action_invalid()
